<template>
    <div class="cont">
        <nav-bar 
            textColor="#333333"
            rightImg="https://h5.dhcc.wang/newprogram/wxRobot/nav_refresh_black.png" 
            title="微信群发单" 
            bgStyle="#fff"
            :rotate.sync="reload" 
            @leftClick="back"
            @rightClick="refresh" />
        <div class="cont-main">
            <div class="font-16 m-t-10 m-b-10 text-bold">① 选择您需要操作的发单群</div>
            <van-skeleton :loading="isLoadingSkeleton" avatar :row="3" v-for="i in 2" :key="i" />
            <div v-for="item in fadanList" :key="item.id" class="fd-item m-b-10" :class="{'active': fdData && fdData.user_name == item.user_name}" @click="handleChange(item)">
                <div class="flex align-center">
                    <img class="group-avatar" :src="item.small_head_img_url" alt="" />
                    <div class="flex-sub group-name">
                        <div 
                            class="van-ellipsis font-14 text-bold">
                            {{item.group_name 
                                ? item.group_name 
                                : item.nick_name}}
                            </div>
                            <div
                                class="m-t-5 text-10 font-12 color-9 van-ellipsis">
                                <van-tag plain type="warning">源头群</van-tag>
                                {{
                                    item.user_name_source_info &&
                                    (item.user_name_source_info.group_name || item.user_name_source_info.nick_name)
                                    || '暂未绑定' }}
                            </div>
                    </div>
                </div>
                <div v-if="fdData && fdData.user_name == item.user_name">
                    <van-icon name="success" size="16" class="active-icon"/>
                </div>
            </div>
            
            <div class="flex justify-between align-center  m-t-20 m-b-5 p-t-5 text-bold">
                <div class="font-16">② 选择您需要跟采的源头群</div>
                <div class="flex align-center">
                    <div class="m-r-10">只看收藏 </div>
                    <van-switch v-model="onlyCollect" size="22"
                                :active-color="config.mac_assist_color" @change="handleSwitchChange" /></div>
            </div>
            
            <!-- 分类 -->
            <template v-if="cateList.length > 1 && !onlyCollect">
                <van-tabs v-model="tabActive" line-width="20" background="transparent" :swipe-threshold="6" @change="tabChange">
                    <van-tab v-for="(item, index) in cateList"  :title="item.name" :key="index"></van-tab>
                </van-tabs>
            </template>


            <van-list
                v-model="loading"
                :finished="finished"
                finished-text="没有更多了"
                v-if="sourceList.length"
                :immediate-check="false"
                @load="onLoad"
                >
                <div class="flex justify-between flex-wrap m-b-10">
                    <div class="source-item m-t-10" :class="{'item-forbid': fdData && fdData.user_name_source == item.user_name}" v-for="(item, index) in sourceList" :key="item.id">
                        <div class="flex align-center">
                            <img class="group-avatar group-avatar-bg" :src="item.small_head_img_url" alt="" />
                            <div class="m-l-10 font-14 text-bold van-multi-ellipsis--l2">
                                {{item.group_name || item.nick_name}}
                            </div>
                        </div>
                        <div class="flex justify-between align-center m-t-5">
                            <div class="color-9 font-11"><van-icon name="todo-list-o" style="top:2px" size="14"/> {{ item.latest_msg_time * 1000 | getDateDiff }}</div>
                            <div 
                                class="group-tag font-11" 
                                :class="item.is_collect === 1 ? 'gray' : ''" 
                                @click.stop="handleChangeCollect(item, index)">{{item.is_collect === 1 ? '已收藏' : '+收藏'}}
                            </div>
                        </div>
                        
                        <div class="flex justify-center m-t-10 text-center">
                            <div class="flex-sub font-12 btn m-r-10" @click="openPage(item)"><van-icon name="eye" style="top:2px"/> 预览</div>
                            <div 
                                class="flex-sub font-12 btn btn-org" 
                                :class="{'btn-forbid': fdData && fdData.user_name_source == item.user_name}" @click="handleSubmit(item)">
                                <van-icon name="checked" style="top:2px"/> {{fdData && fdData.user_name_source == item.user_name ? '已绑定' : '绑定'}}
                            </div>
                        </div>
                    </div>
                </div>
            </van-list>
            <noData marginTop="100px" v-else />
        </div>
    </div>
</template>

<script>
import { Notify, Tag, Tab, Tabs, List, Switch } from 'vant'
import noData from '@/components/noData'
export default {
    components: {
        noData,
        [Notify.name]: Notify,
        [Tag.name]: Tag,
        [Tabs.name]: Tabs,
        [Tab.name]: Tab,
        [List.name]: List,
        [Switch.name]: Switch
    },
    data () {
        return {
            config: this.$DB.get('robotCfg'),
            reload: false,
            currentUsername: '',
            isLoadingSkeleton: true,
            fadanList: [], // 发单群列表
            sourceList: [], // 源头群列表
            fdData: null, // 选中的发单群
            cateList: [{
                id: '',
                name: '全部'
            }],
            tabActive: 0,
            loading: false,
            finished: false,
            currentPage: 1,
            pageSize: 10,
            onlyCollect: false
        }
    },
    created () {
        let username = this.$route.query.username || ''
        this.currentUsername = decodeURIComponent(username)
        if (this.currentUsername) {
            this.getContactDetail()
        }
        this.init()
        this.setHeader()
    },
    mounted () {
        let userAgent = navigator.userAgent
        let isIOS = !!userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)
        if (isIOS) {
            window.addEventListener('pageshow', this.setHeader, false)
        }
    },
    methods: {
        init () {
            this.tabActive = 0
            this.getFdList()
            this.getCateList().then(res => {
                res.list.unshift({
                    id: '',
                    name: '全部'
                })
                this.cateList = res.list
                this.getSourceList(true)
            })
        },
        // 源头群分类
        getCateList () {
            return new Promise(resolve => {
                this.$api.getGroupCate().then(res => {
                    if (res.code == 1) {
                        resolve(res.data)
                    }
                }).catch(() => {})
            })
        },
        tabChange (index) {
            this.tabActive = index
            this.getSourceList(true)
        },
        getContactDetail () {
            this.$api.contactDetail({
                username: this.currentUsername
            }).then(res => {
                if (res.code == 1) {
                    this.fdData = JSON.parse(JSON.stringify(res.data))
                }
            }).catch(() => {})
        },
        setHeader () {
            this.$common.setHeader({
                native_headershow: 0,
                topstyle: 'topcolor',
                native_top_words_color: '#ffffff',
                str_link_color: '#ffffff',
                end_link_color: '#ffffff'
            })
        },
        // 获取发单群列表
        getFdList () {
            this.$api.getListGroup({
                group_type: 2,
                status: -1,
                page: 1,
                pagesize: 30
            }).then(res => {
                const { list = [] } = res.data
                this.fadanList = list
                this.isLoadingSkeleton = false
            }).catch(() => {
                this.isLoadingSkeleton = false
            })
        },
        getSourceList (isFirst) {
            if (isFirst) {
                this.currentPage = 1
                this.sourceList = []
                this.finished = false
            }
            let http = null
            if (this.onlyCollect) { // 只看收藏
                http = this.$api.collectList({
                    pagesize: this.pageSize,
                    page: this.currentPage
                })
            } else {
                http = this.$api.getListSource({
                    cate_id: this.tabActive == 0 ? '' : this.cateList[this.tabActive].id,
                    pagesize: this.pageSize,
                    page: this.currentPage
                })
            }
            http.then(res => {
                this.loading = false
                const { list = [], total = 0 } = res.data
                this.sourceList = [...this.sourceList, ...list]
                this.currentPage++
                if (this.sourceList.length >= total) {
                    this.finished = true
                }
            }).catch(() => {}).finally(() => {
                setTimeout(() => {
                    this.reload = false
                    this.loading = false
                }, 300)
            })
        },
        onLoad () {
            this.loading = true
            this.getSourceList()
        },
        // 切换发单群
        handleChange (item) {
            this.fdData = JSON.parse(JSON.stringify(item))
        },
        back () {
            this.$router.go(-1)
        },
        refresh () {
            this.reload = true
            this.init()
        },
        openPage (item) {
            let params = {
                // id: encodeURIComponent(this.currentUsername), // 发单群ID
                username: encodeURIComponent(item.user_name), // 源头群ID
                name: encodeURIComponent(item.group_name || item.nick_name),
                status: this.fdData ? this.fdData.status : 0, // 发单群开关状态
                showBottom: 1,
                owner: item.owner
            }
            if (this.fdData && this.fdData.user_name_source != item.user_name) {
                params.id = encodeURIComponent(this.fdData.user_name)
            }
            let theUrl = `${process.env.VUE_APP_JUMP_URL}?xid=${global.getUrlName('xid')}#/history?params=${JSON.stringify(params)}`
            window.location.href = theUrl
        },
        handleSubmit (item) {
            if (!this.fdData) {
                Notify({
                    type: 'danger',
                    message: '请选择需要操作的群^_^',
                    duration: '800'
                })
                this.$common.setHeader({
                    str_link_color: '#ee0a24',
                    end_link_color: '#ee0a24'
                })
                setTimeout(() => {
                    this.setHeader()
                }, 1000)
            }
            if (this.fdData.user_name_source == item.user_name) {
                return
            }
            this.$dialog.confirm({
                title: '提示',
                message: `确认绑定“${item.group_name || item.nick_name}”？`
            }).then(() => {
                this.$api.updateGroup({
                    username: decodeURIComponent(this.fdData.user_name),
                    username_source: decodeURIComponent(item.user_name),
                    group_type: 2,
                    status: this.fdData.status || 0
                }, false).then(res => {
                    if (res.code == 1) {
                        Notify({
                            type: 'success',
                            message: '绑定成功^_^',
                            duration: '800'
                        })
                        this.$common.setHeader({
                            str_link_color: '#07c160',
                            end_link_color: '#07c160'
                        })
                        setTimeout(() => {
                            this.setHeader()
                            this.currentUsername = this.fdData.user_name
                            this.refresh()
                            this.getContactDetail()
                        }, 1000)
                    } else {
                        this.$toast(res.msg)
                    }
                }).catch(() => {})
            })
        },
        // 添加/取消收藏
        handleChangeCollect (item, index) {
            let is_collect = item.is_collect
            this.$api.setCollect({
                user_name: item.user_name,
				owner: item.owner,
                type: is_collect === 1 ? 2 : 1 // 2 取消收藏 1 添加收藏
            }).then(res => {
                item.is_collect = is_collect === 1 ? 0 : 1
                this.$toast(is_collect === 1 ? '取消收藏' : '收藏成功')
                if (this.onlyCollect) {
                    this.sourceList.splice(index, 1)
                }
            })
        },
        handleSwitchChange (val) {
            this.onlyCollect = val
            this.getSourceList(true)
        }
    },
    destroyed () {
        window.removeEventListener('pageshow', this.setHeader)
    }
}
</script>
<style lang="less" scoped>
::v-deep .van-tabs__wrap {
    touch-action: pan-x;
    .van-tabs__nav--line {
        padding-bottom: 10px;
    }
    .van-tabs__line {
        background: #111111;
    }
    .van-tab--active {
        font-size: 15px;
        color: #111111;
        font-weight: bold;
    }
    .van-tabs__nav--complete {
        padding-left: 0;
    }
}
.cont{
    font-size: 14px;
    padding-top: 46px;
    &-main{
        padding: 12px;
        .fd-item {
            position: relative;
            width: 100%;
            padding: 12px;
            background: #fff;
            border-radius: 10px;
            background-color: hsla(0,0%,100%,.7);
            border: 1px solid #fff;
            box-shadow: 0 18px 30px -16px rgba(157,160,170,.31);
            box-sizing: border-box;
            .active-icon {
                position: absolute;
                right: -1px;
                bottom: -1px;
                background: #ed6a0c;
                color: #ffffff;
                border-radius: 5px 0 8px 0;
                padding: 1px 4px;
                // transform: translateY(-50%);
            }
            &.active {
                background: #fffbe8 !important;
                color: #ed6a0c;
                border-color: #faaf79;
            }
            .group-name {
                overflow: hidden;
            }
        }
        .source-item {
            width: calc(50.0vw - 38px);
            padding: 12px 10px;
            border-radius: 10px;
            background-color: hsla(0,0%,100%,.7);
            border: 1px solid #fff;
            box-shadow: 0 18px 30px -16px rgba(157,160,170,.31);
            // box-sizing: border-box;
            &.item-forbid {
                background: #f1fced;
                border-color: #a3c0ac;
            }
        }
        .group-avatar{
            width: 44px;
            height: 44px;
            margin-right: 15px;
            border-radius: 4px;
            box-shadow: 0 13px 16px -9px rgba(0,0,0,.25);
            &.group-avatar-bg {
                width: 42px;
                height: 42px;
                margin-right: 0;
                box-shadow: 0 13px 16px -9px rgba(0,0,0,.25);
                // margin-top: 5px;
            }
        }
        .btn {
            padding: 3px 5px 4px;
            color: #333333;
            border: 1px solid #dddddd;
            border-radius: 20px;
            &-org {
                border: 1px solid #07c160;
                color: #07c160;
            }
            &-forbid {
                background: #07c160;
                color: #ffffff;
            }
        }
    }
}
.group-tag {
    padding: 0 5px;
    // background: rgba(135, 181, 255, 0.2);
    // color: #3b84fb;
    background: #F5F8FF;
    color: #4D75FF;
    border-radius: 2px;
    &.gray {
        background: #fef4eb;
        color: #f55a00
    }
}
</style>